package com.planesnet.task1;

import helper.MySQLiteHelper;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class Task {
	private static MySQLiteHelper dbHelper;
	
	// Database fields
	private static SQLiteDatabase database;
	
	private static String[] allColumns = { MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_NAME };

	private long id;
	private String name;

	public Task() {

	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// Will be used by the ArrayAdapter in the ListView
	@Override
	public String toString() {
		return name;
	}

	

	

	public Task create() {
		if(database==null) {
			open();
		}
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_NAME, name);
		long insertId = database.insert(MySQLiteHelper.TABLE_TASKS, null,
				values);
		// To show how to query
		Cursor cursor = database.query(MySQLiteHelper.TABLE_TASKS, allColumns,
				MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null,
				null);
		cursor.moveToFirst();
		
		close();
		return cursorToTask(cursor);
		
	}

	public void delete() {
		if(database==null) {
			open();
		}
		System.out.println("Task deleted with id: " + this.id);
		database.delete(MySQLiteHelper.TABLE_TASKS, MySQLiteHelper.COLUMN_ID
				+ " = " + id, null);
		System.out.println("delete");
		close();
	}

	public static List<Task> getAll() {
		List<Task> tasks = new ArrayList<Task>();
		if(database==null) {
			open();
		}
		Cursor cursor = database.query(MySQLiteHelper.TABLE_TASKS, allColumns,
				null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Task task = cursorToTask(cursor);
			tasks.add(task);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return tasks;
	}

	
	public static void setContext(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}
	
	private static Task cursorToTask(Cursor cursor) {
		Task task = new Task();
		task.setId(cursor.getLong(0));
		task.setName(cursor.getString(1));
		return task;
	}
	private static void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	private static void close() {
		dbHelper.close();
		database=null;
	}
}